package com.dc.kylin.integration.task;

import com.dc.kylin.integration.chche.TokenCache;
import com.dc.kylin.integration.lock.RedisDistributedLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class TokenRefreshTask {

    private static final String TASK_NAME = "tokenRefreshTask";
    //节点，动态生成
    private static final String NODE_IDENTIFIER = "node-1";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private TokenCache tokenCache;
    @Autowired
    private RedisDistributedLock redisDistributedLock;

    @Scheduled(fixedRate = 60 * 1000)
    public void refreshTokenTask(){
        if(redisDistributedLock.tryAcquireLock(TASK_NAME,NODE_IDENTIFIER)){
            try {
                Set<String> keys = redisTemplate.keys(TokenCache.TOKEN_CACHE_PREFIX);
                if(keys !=null && keys.size() > 0){
                    for (String key : keys) {
                        Long ttl = redisTemplate.getExpire(key, TimeUnit.SECONDS);
                        if(ttl != null && ttl <= TokenCache.REFRESH_TOKEN_EXPIRE_TIME){
                            tokenCache.reflushToken(key.replace(TokenCache.TOKEN_CACHE_PREFIX,""));
                            System.out.println("refresh token success" + key);
                        }
                    }
                }
            } finally {
                System.out.println("token refresh task end");
                redisDistributedLock.releaseLock(TASK_NAME,NODE_IDENTIFIER);
            }
        }else {
            System.out.println("刷新任务已经被其他节点执行了....");
        }
    }
}
